import os
import uuid
from flask import Flask, request, jsonify, send_from_directory, render_template
from v2appconversationruns import start_conversation, upload_file, run_conversation

app = Flask(__name__)
UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/imageDetect', methods=['POST'])
def image_detect():
    if 'image' not in request.files:
        return jsonify({'success': False, 'message': '没有文件部分'})

    file = request.files['image']
    if file.filename == '':
        return jsonify({'success': False, 'message': '没有选择文件'})

    if file and allowed_file(file.filename):
        filename = str(uuid.uuid4()) + '_' + file.filename
        filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        file.save(filepath)

        # 从请求中获取用户输入的问题
        question = request.form.get('question')

        # 启动对话并获取 conversation_id
        conversation_id = start_conversation()

        # 上传文件并获取 file_id
        file_id = upload_file(conversation_id, filepath)

        # 运行对话并获取识别结果
        response_data = run_conversation(conversation_id, file_id, question)
        answer = response_data.get('answer', '未找到答案')

        return jsonify({'success': True, 'answer': answer, 'progress': '识别完毕'})
    else:
        return jsonify({'success': False, 'message': '文件类型不允许'})

if __name__ == '__main__':
    if not os.path.exists(UPLOAD_FOLDER):
        os.makedirs(UPLOAD_FOLDER)
    app.run(debug=True)